package br.edu.ifrn.tads.pontos.o;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@SuppressLint("SetJavaScriptEnabled")
public class PontosWebActivity extends Activity  {

	WebView myWebView;
	SharedPreferences.Editor prefsEditor;
	boolean backToLogin;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pontos_web);

//		final ActionBar actionBar = getActionBar();
		String url = String.format(Globals.SERVER_URL+"/panel/mobile?mobile=true&email=%s&senha=%s",getIntent().getSerializableExtra("email"),getIntent().getSerializableExtra("senha"));
		//		Toast.makeText(this, url, Toast.LENGTH_LONG).show();
		prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();

		myWebView = (WebView) findViewById(R.id.webview);
		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		myWebView.addJavascriptInterface(this, "Android");
		backToLogin = getIntent().getExtras().getBoolean("backtologin");
		webSettings.setLightTouchEnabled(true);
		myWebView.setWebViewClient(new WebViewClient() {  
			@Override  
			public boolean shouldOverrideUrlLoading(WebView view, String url)  
			{  
				return false;
			} 
			public void onReceivedError (WebView view, int errorCode, String description, String failingUrl){
				String msg="<h2>Erro desconhecido</h2>";
//				Toast.makeText(PontosWebActivity.this, ""+errorCode, Toast.LENGTH_LONG).show();
				
				if (errorCode<0){
					msg = "<h2>:/<br />Sua Internet est&aacute; desconectada. </h2>";
				}
				else if (errorCode == 503){
					msg = "<h2>:/<br />O servi&ccedil;o est&aacute; fora do ar.</h2>";
				}
				else if (errorCode == 500){
					msg = "<h2>:/<br />Falha no servi&ccedil;o de jogo.</h2>";
				}
				
				
				view.loadData(msg, "text/html", "utf-8");
			}

		});  
		myWebView.loadUrl(url);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
			myWebView.goBack();
			return true;
		}
		else if  (keyCode == KeyEvent.KEYCODE_BACK){
			if (backToLogin){
				Intent goLogin = new Intent(getBaseContext(), MainActivity.class);
				goLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(goLogin);
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.pontos_web, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.logout:
			prefsEditor.remove("senha");
			prefsEditor.commit();
			Intent goLogin = new Intent(getBaseContext(), MainActivity.class);
			goLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(goLogin);
			finish();
			break;

		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	//
	@JavascriptInterface
	public void alerta(String mensagem, final String urlredirect){
		new AlertDialog.Builder(this)
		.setMessage(mensagem)
		.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				myWebView.loadUrl(Globals.SERVER_URL+urlredirect);
			}
		})
		.create()
		.show();
	}

}
